package com.ccc.demoboot.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.ccc.demoboot.common.R;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Random;

/**
 * 自己写的一个通用的controller的父类
 * 提供针对于任何表的的单表的增删改查的操作
 */
public class BaseController<S extends IService,E> {


    @Autowired
    private S iservice;

    /**
     * 根据主键id删除一条数据
     * @param id
     * @return
     */
    @GetMapping("/deleteentitybyid/{id}")
    public R deleteEntityById(@PathVariable("id") Integer id){
        this.iservice.removeById(id);
        return new R().addDatamap("message","删除数据成功");
    }

    /**
     * 根据主键id查询一个对象
     * @param id  id值
     * @return 返回一个对象
     */
    @GetMapping("/selectentitybyid/{id}")
    public  R selectEntityByid(@PathVariable("id") Integer id){
       E obj=(E)this.iservice.getById(id);
       return new R().addDatamap("obj",obj);
    }

    /**
     * 根据主键id修改一个对象
     * @param obj  要修改的对象
     * @return
     */
    @PostMapping("/updateentitybyid")
    public  R updateEntityByid(@RequestBody E obj){
        this.iservice.updateById(obj);
        return new R().addDatamap("message","修改数据成功");
    }

    /**
     * 根据对象属性条件查询返回list集合（分页）
     */
    @CrossOrigin(origins = "*")
    @GetMapping("/selectentitylistwhere/{nowpage}")
    public R selectEntityListWhere(E obj,@PathVariable("nowpage") Integer nowpage){
        PageHelper.startPage(nowpage,5);

        QueryWrapper<E> objectQueryWrapper = new QueryWrapper<>();
        objectQueryWrapper.setEntity(obj);
        List<E> list = this.iservice.list(objectQueryWrapper);

        PageInfo<E> ePageInfo = new PageInfo<>(list);
        return new R().addDatamap("pageinfo",ePageInfo);
    }


    /**
     * 增加一个单表对象
     * @param obj
     * @return
     */
    @GetMapping("/addentity")
    public R addEntity(E obj){
        this.iservice.save(obj);
        return new R().addDatamap("message","增加数据成功");
    }



    public S getIservice() {
        return iservice;
    }

    public void setIservice(S iservice) {
        this.iservice = iservice;
    }


}
